import store from "../store";
class WSClient {
  /**
   * 构造器
   */
  constructor(userId, callback) {
    console.log(222222222222222222);
    this.ws = "";
    this.userId = userId;
    this.callback = callback;
    this.message = `{
            "action": "1",
            "chatMsg": {
                "senderId": "${userId}web",
                "receiverId": "",
                "msg": "",
                "msgId": ""
            },
            "extend": ""
        }`;
    this.connect();
  }

  changePjt(userId) {
    this.close();
    this.message = `{
            "action": "1",
            "chatMsg": {
                "senderId": "${userId}web",
                "receiverId": "",
                "msg": "",
                "msgId": ""
            },
            "extend": ""
        }`;
    this.connect();
  }

  /**
   * 建立websocket连接
   */
  connect() {
    // this.ws = new WebSocket(store.state.wsUrl);
    // this.ws = new WebSocket(`ws://8.129.97.134:8082/ws?userId=${this.userId}web`);
    this.ws = new WebSocket(`${store.state.wsUrl}?userId=${this.userId}web`);
    this.initEventHandle();
  }

  /***
   * @发送初始化数据
   */
  sendInitData() {
    this.ws.send(this.message);
  }

  /**
   * 初始化websocket监听事件
   */
  initEventHandle() {
    this.ws.onopen = (ev) => {
      this.openEventHandle(ev);
    };
    this.ws.onmessage = (ev) => {
      this.messageEventHandle(ev);
    };
    this.ws.onerror = (ev) => {
      this.errorEventHandle(ev);
    };
    this.ws.onclose = (ev) => {
      this.closeEventHandle(ev);
    };
  }

  /**
   * 连接建立成功后的监听事件
   */
  openEventHandle(ev) {
    // store.commit('saveWSStatus', true)
    // console.log('连接成功')
    this.sendInitData();
    this.heartCheck();
  }

  /**
   * 接收消息的监听事件
   */
  messageEventHandle(ev) {
    // this.heartCheck();
    let data = JSON.parse(ev.data);
    this.callback(data);
  }

  /**
   * 连接异常的监听事件
   */
  errorEventHandle(ev) {
    // console.log(ev, "连接异常")
    this.reconnect();
  }

  /**
   * 连接关闭的监听事件
   */
  closeEventHandle(ev) {
    // store.commit('saveWSStatus', false)
    // console.log('关闭了连接');
  }

  /**
   * 重连
   */
  reconnect() {
    this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
    this.reconnectTimeout = setTimeout(() => {
      this.connect();
    }, 1000);
  }

  /**
   * 断开websocket连接
   */
  close() {
    this.clearTimeout();
    this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
    this.ws.close();
  }

  /**
   * 心跳检测
   */
  heartCheck() {
    this.clearTimeout();
    this.timeout = setInterval(() => {
      this.ws.send(this.message);
    }, 50000);
  }

  clearTimeout() {
    this.timeout && clearTimeout(this.timeout);
  }
}

export default WSClient;
